var url = require('url');
var http = require('http');
var util = require('util');
var fs = require('fs');
const https = require('https');
var querystring = require('querystring');

module.exports = {
	// 得到微信access_token
	get_access_token: function(req, res) {
		var appid = "wxb226d4704543d336";
		var appsecretc = "a35af755576add86cef449c91860ba60";

		https.get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + appid + '&secret=' +
			appsecretc, (resp) => {
				let data = '';
				resp.on('data', (chunk) => {
					data += chunk;
				});
				resp.on('end', () => {
					// console.log(`状态码: ${data.access_token}`);
					console.log(data, typeof data);
					res.end(data)
					var dd = JSON.parse(data)
					// console.log(`状态码:ta.access_token---`, dd);
					rwm(dd.access_token)
				});
			}).on("error", (err) => {
			console.log("Error2: " + err.message);
		});



		function rwm(access_token) {
			const postData = querystring.stringify({
				"expire_seconds": 604800,
				"action_name": "QR_STR_SCENE",
				"action_info": {
					"scene": {
						"scene_str": "2242"
					}
				}
			});

			var url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + access_token;

			const req2 = http.request(new URL(url), (res) => {
				// console.log(`状态码: ${res.statusCode}`);
				// console.log(`响应头: ${JSON.stringify(res.headers)}`);
				res.setEncoding('utf8');
				var data;
				res.on('data', (chunk) => {
					data += chunk;
					console.log(`响应主体: ${chunk}`);
					
				});
				res.on('end', () => {
					console.log('响应中已无数据');
					console.log('响应中已无数据__```~~~', data);
				});
			});
			req2.on('error', (e) => {
			  console.error(`请求遇到问题: ${e.message}`);
			});
			req2.write(postData);
			req2.end();
		}




	},

	// 访问一个文件
	fs: function(req, res) {
		res.writeHeader(200, {
			"Content-type": "text/html;charset=utf8"
		})
		res.write("hello, 你拖拖看看看");
		var data = '';
		var readerStream = fs.createReadStream('./route/ttt.html');
		readerStream.setEncoding('UTF8');
		readerStream.on('data', function(chunk) {
			data += chunk;
		});
		readerStream.on('end', function() {
			// res.end(data);
			res.end("<br/>	success");
		});
		readerStream.on('error', function(err) {
			console.log(err.stack);
		});
	}
}
